/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 21/11/2011, 16:17:01
 */

package proj5labbd.graphics;

import java.util.logging.Level;
import java.util.logging.Logger;
import proj5labbd.graphics.abstractOpGraphics.OperationFrame;
import proj5labbd.exceptions.NullConnection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import proj5labbd.DBConnector;
import proj5labbd.DBMainInterface;
import proj5labbd.DateUtils;
import proj5labbd.ScriptReader;
import proj5labbd.graphics.comercial.ComercialFrame;
import proj5labbd.graphics.consultas.ProgFrame;
import proj5labbd.graphics.consultas.SerieFrame;
import proj5labbd.graphics.consultas.SalarioFrame;
import proj5labbd.graphics.departamento.DeptFrame;
import proj5labbd.graphics.dependente.DepFrame;
import proj5labbd.graphics.emissora.EmissoraFrame;
import proj5labbd.graphics.exibicaoComercial.ExCoFrame;
import proj5labbd.graphics.exibicaoJornal.ExJoFrame;
import proj5labbd.graphics.funcionario.FuncionarioFrame;
import proj5labbd.graphics.jornal.JornalFrame;
import proj5labbd.graphics.relatorios.RelatorioDept;
import proj5labbd.graphics.relatorios.RelatorioIbope;
import proj5labbd.graphics.relatorios.TempoTotalFunc;
import proj5labbd.graphics.tipoFuncionario.TipoFuFrame;
import proj5labbd.graphics.trabalho.TrabFrame;

/*
 * Frame principal do aplicativo, armazena todos os frames utilizados
 * bem como conexão com o SGBD e uma DBInterface
 */
public class MainFrame extends javax.swing.JFrame {

    private ConnFrame frmConn;
    private OperationFrame frmEmissora;
    private OperationFrame frmDept;
    private OperationFrame frmTipoFu;
    private OperationFrame frmFunc;
    private OperationFrame frmDependente;
    private OperationFrame frmTrabalho;
    private OperationFrame frmExJo;
    private OperationFrame frmExCo;
    private OperationFrame frmJornal;
    private OperationFrame frmTrab;
    private OperationFrame frmCom;
    private OperationFrame frmSeries;
    private OperationFrame frmIbope;
    private OperationFrame frmSalarios;
    private DBConnector dbConn;
    private DBMainInterface dbInterface;
    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        this.setResizable(false);
        //Conexão localhost... utilização específica
        dbConn = new DBConnector();
        dbConn.setIP("127.0.0.1");
        dbConn.setPort(1521);
        dbConn.setUser("a5881819");
        try {
            dbConn.start("a5881819");
        } catch (SQLException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NullConnection ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        dbInterface = new DBMainInterface(dbConn);
        //construção dos frames
        frmConn = new ConnFrame(this);
        frmEmissora = new EmissoraFrame(this, dbInterface);
        frmTrabalho = new TrabFrame(this, dbInterface);
        frmExJo = new ExJoFrame(this, dbInterface);
        frmDept = new DeptFrame(this, dbInterface);
        frmTipoFu = new TipoFuFrame(this, dbInterface);
        frmFunc = new FuncionarioFrame(this, dbInterface);
        frmDependente = new DepFrame(this,dbInterface);
        frmJornal = new JornalFrame(this,dbInterface);
        frmCom = new ComercialFrame(this,dbInterface);
        frmExCo = new ExCoFrame(this,dbInterface);
        frmSeries = new SerieFrame(this, dbInterface);
        frmIbope = new ProgFrame(this, dbInterface);
        frmSalarios = new SalarioFrame(this, dbInterface);

        MainAction act = new MainAction();
        //registro dos ouvintes
        jmnitConnect.addActionListener(act);
        jmnitConnClose.addActionListener(act);
        jmnitReset.addActionListener(act);
        jmnitDept.addActionListener(act);
        jmnitFunc.addActionListener(act);
        jmnitDepend.addActionListener(act);
        jmnitTrabalho.addActionListener(act);
        jmnitExJo.addActionListener(act);
        jmnitComercial.addActionListener(act);
        jmnitExCo.addActionListener(act);
        jmnitJornal.addActionListener(act);
        jmnitSeries.addActionListener(act);
        jmnitSal.addActionListener(act);
        jmnitIbope.addActionListener(act);
        jmnitRelDept.addActionListener(act);
        jmnitTempo.addActionListener(act);
        jmnitDeptIbope.addActionListener(act);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnlFrame = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtxaException = new javax.swing.JTextArea();
        jmnMain = new javax.swing.JMenuBar();
        jmnConnect = new javax.swing.JMenu();
        jmnitConnect = new javax.swing.JMenuItem();
        jmnitConnClose = new javax.swing.JMenuItem();
        jmnTables = new javax.swing.JMenu();
        jmnitDept = new javax.swing.JMenuItem();
        jmnitFunc = new javax.swing.JMenuItem();
        jmnitDepend = new javax.swing.JMenuItem();
        jmnitTrabalho = new javax.swing.JMenuItem();
        jnmJornal = new javax.swing.JMenu();
        jmnitJornal = new javax.swing.JMenuItem();
        jmnitExJo = new javax.swing.JMenuItem();
        jnmCom = new javax.swing.JMenu();
        jmnitComercial = new javax.swing.JMenuItem();
        jmnitExCo = new javax.swing.JMenuItem();
        jmnitValorCo = new javax.swing.JMenuItem();
        jmnRelat = new javax.swing.JMenu();
        jmnitRelDept = new javax.swing.JMenuItem();
        jmnitTempo = new javax.swing.JMenuItem();
        jmnitDeptIbope = new javax.swing.JMenuItem();
        jmnCons = new javax.swing.JMenu();
        jmnitSeries = new javax.swing.JMenuItem();
        jmnitSal = new javax.swing.JMenuItem();
        jmnitIbope = new javax.swing.JMenuItem();
        jmnReset = new javax.swing.JMenu();
        jmnitReset = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("jfrmMain"); // NOI18N

        jtxaException.setColumns(20);
        jtxaException.setLineWrap(true);
        jtxaException.setRows(5);
        jScrollPane1.setViewportView(jtxaException);

        javax.swing.GroupLayout jpnlFrameLayout = new javax.swing.GroupLayout(jpnlFrame);
        jpnlFrame.setLayout(jpnlFrameLayout);
        jpnlFrameLayout.setHorizontalGroup(
            jpnlFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnlFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                .addContainerGap())
        );
        jpnlFrameLayout.setVerticalGroup(
            jpnlFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnlFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
                .addContainerGap())
        );

        jmnConnect.setText("Conexão");
        jmnConnect.setActionCommand("Connect");

        jmnitConnect.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jmnitConnect.setLabel("Open");
        jmnConnect.add(jmnitConnect);

        jmnitConnClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jmnitConnClose.setLabel("Close");
        jmnConnect.add(jmnitConnClose);

        jmnMain.add(jmnConnect);

        jmnTables.setText("Tabelas");

        jmnitDept.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jmnitDept.setText("Departamento");
        jmnTables.add(jmnitDept);

        jmnitFunc.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jmnitFunc.setText("Funcionário");
        jmnTables.add(jmnitFunc);

        jmnitDepend.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jmnitDepend.setText("Dependentes");
        jmnTables.add(jmnitDepend);

        jmnitTrabalho.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jmnitTrabalho.setText("Trabalho");
        jmnTables.add(jmnitTrabalho);

        jnmJornal.setText("Jornal");

        jmnitJornal.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jmnitJornal.setText("Jornal");
        jnmJornal.add(jmnitJornal);

        jmnitExJo.setText("Exibição de Jornal");
        jnmJornal.add(jmnitExJo);

        jmnTables.add(jnmJornal);

        jnmCom.setText("Comercial");

        jmnitComercial.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jmnitComercial.setText("Comercial");
        jnmCom.add(jmnitComercial);

        jmnitExCo.setText("Exibição de Comercial");
        jnmCom.add(jmnitExCo);

        jmnitValorCo.setText("Valor de Comercial");
        jnmCom.add(jmnitValorCo);

        jmnTables.add(jnmCom);

        jmnMain.add(jmnTables);

        jmnRelat.setText("Relatórios");

        jmnitRelDept.setText("Departamento");
        jmnRelat.add(jmnitRelDept);

        jmnitTempo.setText("Tempo de trabalho");
        jmnRelat.add(jmnitTempo);

        jmnitDeptIbope.setText("Ibope dos departamentos");
        jmnRelat.add(jmnitDeptIbope);

        jmnMain.add(jmnRelat);

        jmnCons.setText("Consultas");

        jmnitSeries.setText("Séries");
        jmnCons.add(jmnitSeries);

        jmnitSal.setText("Média de salário");
        jmnCons.add(jmnitSal);

        jmnitIbope.setText("Média de ibope");
        jmnCons.add(jmnitIbope);

        jmnMain.add(jmnCons);

        jmnReset.setText("Reset");

        jmnitReset.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
        jmnitReset.setText("Reset");
        jmnReset.add(jmnitReset);

        jmnMain.add(jmnReset);

        setJMenuBar(jmnMain);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jpnlFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jpnlFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenu jmnConnect;
    private javax.swing.JMenu jmnCons;
    private javax.swing.JMenuBar jmnMain;
    private javax.swing.JMenu jmnRelat;
    private javax.swing.JMenu jmnReset;
    private javax.swing.JMenu jmnTables;
    private javax.swing.JMenuItem jmnitComercial;
    private javax.swing.JMenuItem jmnitConnClose;
    private javax.swing.JMenuItem jmnitConnect;
    private javax.swing.JMenuItem jmnitDepend;
    private javax.swing.JMenuItem jmnitDept;
    private javax.swing.JMenuItem jmnitDeptIbope;
    private javax.swing.JMenuItem jmnitExCo;
    private javax.swing.JMenuItem jmnitExJo;
    private javax.swing.JMenuItem jmnitFunc;
    private javax.swing.JMenuItem jmnitIbope;
    private javax.swing.JMenuItem jmnitJornal;
    private javax.swing.JMenuItem jmnitRelDept;
    private javax.swing.JMenuItem jmnitReset;
    private javax.swing.JMenuItem jmnitSal;
    private javax.swing.JMenuItem jmnitSeries;
    private javax.swing.JMenuItem jmnitTempo;
    private javax.swing.JMenuItem jmnitTrabalho;
    private javax.swing.JMenuItem jmnitValorCo;
    private javax.swing.JMenu jnmCom;
    private javax.swing.JMenu jnmJornal;
    private javax.swing.JPanel jpnlFrame;
    private javax.swing.JTextArea jtxaException;
    // End of variables declaration//GEN-END:variables

    class MainAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            //Abrir Conexão
            if (e.getSource() == jmnitConnect) {
                frmConn.setVisible(true);
            }
            //Fechar Conexão
            if (e.getSource() == jmnitConnClose) {
                try {
                        dbConn.stop();
                        printPrompt("Disconnected.");
                } catch (SQLException ex) {
                    printException(ex);
                    JOptionPane.showMessageDialog(null,"Exception returned by SGBD.");
                } catch (NullConnection ex) {
                    printException(ex);
                    JOptionPane.showMessageDialog(null,"Database connection does not exist.");
                }
            }

            //Resetar a base de dados.. não tenho certeza se há a mesma
            //aceitação sintática do sqldeveloper
            if (e.getSource() == jmnitReset) {
                try {
                    dbInterface.executeDDL(ScriptReader.read("scriptCriaInsere.sql"));
                } catch (SQLException ex) {
                    printException(ex);
                    JOptionPane.showMessageDialog(null,"DDL Script with errors.");
                } catch (FileNotFoundException ex) {
                    printException(ex);
                    JOptionPane.showMessageDialog(null,"DDL Script file not found.");
                } catch (IOException ex) {
                    printException(ex);
                    JOptionPane.showMessageDialog(null,"Error while opening DDL Script file.");
                }
            }
            //Departamento
            if (e.getSource() == jmnitDept) {
                frmDept.setVisible(true);
            }
       
            //Funcionário
            if (e.getSource() == jmnitFunc) {
                frmFunc.setVisible(true);
            }
            //Dependente
            if (e.getSource() == jmnitDepend) {
                frmDependente.setVisible(true);
            }
            //Trabalho
            if (e.getSource() == jmnitTrabalho) {
                frmTrabalho.setVisible(true);
            }
            //ExibicaoJornal
            if (e.getSource() == jmnitExJo) {
                frmExJo.setVisible(true);
            }
            //ExibicaoComercial
            if (e.getSource() == jmnitExCo) {
                frmExCo.setVisible(true);
            }
            //Jornal
            if (e.getSource() == jmnitJornal) {
                frmJornal.setVisible(true);
            }
            //Comercial
            if (e.getSource() == jmnitComercial) {
                frmCom.setVisible(true);
            }
            //Series Consultas
            if (e.getSource() == jmnitSeries) {
                frmSeries.setVisible(true);
            }
            //Salario Consultas
            if (e.getSource() == jmnitSal) {
                frmSalarios.setVisible(true);
            }
            //Ibope Consultas
            if (e.getSource() == jmnitIbope) {
                frmIbope.setVisible(true);
            }
            //Departamento Relatório
            if (e.getSource() == jmnitRelDept) {
                String dept = JOptionPane.showInputDialog("Deseja fazer o relatório de qual departamento?");
               
                RelatorioDept rel = new RelatorioDept(dbInterface,dept);
                rel.setVisible(true);
            }
            //Tempo de trabalho Relatório
            if (e.getSource() == jmnitTempo) {
                TempoTotalFunc rel = new TempoTotalFunc(dbInterface);
                rel.setVisible(true);
            }
            //Ibope médio por departamento - Relatório
            if (e.getSource() == jmnitDeptIbope) {
                RelatorioIbope rel = new RelatorioIbope(dbInterface);
                rel.setVisible(true);
            } 

        }

    }

    //imprime exceções no "terminal"
    public void printException(Exception ex) {
        jtxaException.append("< " + DateUtils.now() + " " + dbConn.getUser() + " > " + ex.getMessage()+"\n" +
                            "--------------------------------------------------------------------------------------------------\n");
    }
    //imprime qualquer conteúdo no "terminal"
    public void printPrompt(String s) {
        jtxaException.append("< " + DateUtils.now() + " " + dbConn.getUser() + " > " + s + "\n" +
                            "--------------------------------------------------------------------------------------------------\n");
    }

    public DBConnector getConn() {
        return dbConn;
    }

}
